package com.lxlg.lxlg_order.common.exceptionhandler;



import com.lxlg.core.exception.LXLGException;
import com.lxlg.core.utils.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

//全局异常处理，
// 类上加RestControllerAdvice
//方法上加@ExceptionHandler

@RestControllerAdvice
public class ProExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public Result handlerArithmeticException(ArithmeticException e){
        e.printStackTrace();
        return Result.getInstance().setCode(5004).setMessage(e.getMessage());
    }

    //空指针异常
    @ExceptionHandler(NullPointerException.class)
    public Result handlerNullPointerException(NullPointerException e){
        e.printStackTrace();
        return Result.getInstance().setCode(5001).setMessage(e.getMessage());
    }
    //转换异常
    @ExceptionHandler(ClassCastException.class)
    public Result handlerClassCastException(ClassCastException e){
        e.printStackTrace();
        return Result.getInstance().setCode(5002).setMessage(e.getMessage());
    }

    //自定义异常
    @ExceptionHandler(LXLGException.class)
    public Result handlerwoniuxyException(LXLGException e) {
        return Result.getInstance().setCode(e.getCode()).setMessage(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e){
        e.printStackTrace();
            return Result.getInstance().setCode(5000).setMessage(e.getMessage());

        }
        //处理后端授权异常
    @ExceptionHandler(AccessDeniedException.class)
    public Result handlerAccessDeniedException(AccessDeniedException e){
        e.printStackTrace();
        return Result.getInstance().setCode(50007).setMessage("未授权");
    }

    // 处理参数校验错误的异常MethodArgumentNotValidException
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        FieldError fieldError = e.getBindingResult().getFieldError();
        return Result.getInstance().setCode(50008).setMessage(fieldError.getDefaultMessage());
    }

}
